#include "protocolprocessservice.h"
#include "log.h"
#include "dataprocessservice.h"
#include <QTextCodec>

ProtocolProcessService::ProtocolProcessService(QObject *parent) : QObject(parent)
{

}

void ProtocolProcessService::process(QByteArray data)
{
    uint8_t* buf = (uint8_t *)data.data();
    uint32_t size = data.size();

    if(buf[0] == (uint8_t)0XB0 && buf[1] == (uint8_t)0XA1)
    {
        uint16_t cmd = (buf[3] << 8) | buf[2];
//        uint16_t len = (buf[5] << 8) | buf[4];
//        uint16_t crc = (buf[size - 1] << 8) | buf[size - 2];

        switch(cmd)
        {

        case 0:
        {
            QByteArray imei((const char *)&buf[6], 15);
            QByteArray time((const char *)&buf[21], 20);
            LOGI("<%s><%s><heartbeat>", time.data(), imei.data());
            break;
        }

        case 2:
        {
            const static QStringList l = {"Online", "Offline", "Lock", "Unlock", "Power Supply", "Battery Supply", "Dead Battery"};
            QByteArray imei((const char *)&buf[6], 15);
            QByteArray time((const char *)&buf[21], 20);
            uint8_t state = buf[41];
            uint8_t SL = state & 0X0F;
            uint8_t SH = (state >> 4) & 0X0F;
            if(SH != 0)
            {
                LOGI("<%s><%s><state>:Probe %d %s", time.data(), imei.data(), SH, l[SL].toStdString().c_str());
            }else
            {
                LOGI("<%s><%s><state>:%s", time.data(), imei.data(), l[SL].toStdString().c_str());
            }
        }

        default:break;
        }
    }else
    {
        buf[size - 2] = 0;  // 去除包尾的回车换行符
        LOGI("\"%s\\r\\n\"", buf);
    }
}
